package com.example.yrdev.ordering_system;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Common.Setting;

import com.example.yrdev.ordering_system.Model.CardTypeInfo;
import com.example.yrdev.ordering_system.Model.Operator;
import com.example.yrdev.ordering_system.User_Login_Register.LoginActivity;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.http.HttpClient;
import com.example.yrdev.ordering_system.http.HttpResponseHandler;
import com.example.yrdev.ordering_system.http.NetWorkConstant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 25/05/2017.
 */

public class SettingActivity extends CommonActivity {

    @InjectView(R.id.ipAddress)EditText ipaddress;
    @InjectView(R.id.port)EditText port;
    @InjectView(R.id.devNo)EditText devNo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.setting_layout);
        initView();


        showRightButtonWithListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //GlobalFunction.showProgress(SettingActivity.this,"正在同步...");
                getSystemSetting();
                getOperatorinfo();
                getAllowCardType();

            }
        },"同步");
    }


    private  void  getSystemSetting(){
        HashMap<String,Object> hashMap=new HashMap<>();

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getSystemSetting,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);

                    Setting.getInstance().parseJSON(respItem,SettingActivity.this);




                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(SettingActivity.this, "sync Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(SettingActivity.this, "无法访问服务器");
            }
        });
    }
    private  void getOperatorinfo(){
        GlobalFunction.ToastAlert(this,"正在同步");
      //  Operator.deleteAllData(this);

        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("operID","");

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getOperatorInfo,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);

                    if (!respItem.isNull("item")){

                        JSONArray jsonArray = respItem.getJSONArray("item");
                        Operator.deleteAllData(SettingActivity.this);// clear
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            Operator operator = new Operator(object);

                            //   if (!existOperator(operator)) {

                            Operator.saveOperator(SettingActivity.this, operator);


                            // }

                            // GoodType.storeToDB(LoginActivity.this,goodType);
                            //   typeAdapter.addJsonObject(object);

                        }

                    }
                    else {

                        GlobalFunction.ToastAlert(SettingActivity.this,"无发现任何操作员");
                    }





            GlobalFunction.ToastAlert(SettingActivity.this,"同步操作员成功");

                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(SettingActivity.this, "Operator Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(SettingActivity.this, "无法访问服务器");
            }
        });
    }

    private  void  getAllowCardType(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("cardType","");

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getAllowCardType,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);


                    JSONArray jsonArray = respItem.getJSONArray("item");
                    CardTypeInfo.deleteAllData(SettingActivity.this);

                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject temp=  jsonArray.getJSONObject(i);
                       // Setting.getInstance().parseAllowCardType(temp);
                        CardTypeInfo.getInstance().addCardTypeList(temp);

                    }

                    GlobalFunction.ToastAlert(SettingActivity.this,"同步卡类成功");

                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(SettingActivity.this, "CardType Fail");

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(SettingActivity.this, "无法访问服务器");
            }
        });
    }

    @Override
    public void initView() {
        super.initView();
        ButterKnife.inject(this);
        ipaddress.setText(NetWorkConstant.defaultIp);
        port.setText(NetWorkConstant.defaultPort);
        devNo.setText(Setting.getInstance().getDevID());


        showBackButton();

        setBarTitle("设置");
    }
    public void save(View view){

       if (checkRequirement()){

        //  Setting.getInstance().saveDevID(devNo.getText().toString());
           String no = devNo.getText().toString();
           Setting.getInstance().setDevID(no);
           Setting.getInstance().saveDevID();
           NetWorkConstant.saveNetwork(this,ipaddress.getText().toString(),port.getText().toString());

           GlobalFunction.ToastAlert(this,"保存成功");
           finish();

       }


    }




    private boolean checkRequirement(){

        if (devNo.getText().toString().length()==0){
            GlobalFunction.ToastAlert(this,"请输入机号");
            return false;

        }



        if (ipaddress.getText().toString().length()==0){
            GlobalFunction.ToastAlert(this,"请输入ip地址");
            return false;

        }else
        if (!NetWorkConstant.isIPAddress(ipaddress.getText().toString())){
            GlobalFunction.ToastAlert(this,"请输入有效ip");
            return false;

        }


        if (port.getText().toString().length()==0){
            GlobalFunction.ToastAlert(this,"请输入端口");
            return false;

        }


        return true;

    }

}
